<template>
  <div class="app-container">
    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="最终发布"></el-step>
    </el-steps>
    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写" />
      </el-form-item>

      <el-form-item label="课程分类">
        <el-select v-model="courseInfo.subjectParentId" placeholder="一级分类" @change="subjectLevelOneChanged">
          <el-option v-for="firstSubject in firstSubjectList" :key="firstSubject.id" :label="firstSubject.title" :value="firstSubject.id"></el-option>
        </el-select>
        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option v-for="secnodSubject in secondSubjectList" :key="secnodSubject.id" :label="secnodSubject.title"
            :value="secnodSubject.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数" />
      </el-form-item>

      <el-form-item label="课程简介">
        <!-- <el-input v-model="courseInfo.description" placeholder="" /> -->
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/eduoss/fileoss'" class="avatar-uploader">
          <img :src="courseInfo.cover" width="300px" height="300px">
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元" /> 元
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import courseService from '@/api/edu/course'
  import subjectService from '@/api/edu/subject'
  // 引入富文本编辑器组件
  import Tinymce from '@/components/Tinymce'

  export default {
    components: {
      Tinymce
    },
    data() {
      return {
        active: 0,
        saveBtnDisabled: false, // 保存按钮是否禁用
        courseInfo: {
          title: '',
          subjectId: '',
          teacherId: '',
          lessonNum: 0,
          description: '',
          cover: '/static/1.jpg',
          price: 0
        },
        BASE_API: process.env.BASE_API,
        teacherList: [],
        firstSubjectList: [],
        secondSubjectList: [],
        courseId: 0
      };
    },
    // watch（监听） 用来解决路由导航问题（修改切换添加时的bug）
    watch: {
      $route(to, from) {
        this.init()
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        if (this.$route.params && this.$route.params.id) {
          this.courseId = this.$route.params.id
          this.getCourseInfo(this.courseId)
        } else {
          this.getAllTeacher()
          this.getAllSubject()
          // ** 变更路由时，调用watch监听，需要把数据清空，但是需要显示指定 subjectId = '' 不然二级分类选择有问题 **
          this.courseInfo = {
            title: '',
            subjectId: '',
            teacherId: '',
            lessonNum: 0,
            description: '',
            cover: '/static/1.jpg',
            price: 0
          }
        }
      },
      getCourseInfo(courseId) {
        courseService.getCourseInfo(this.courseId).then(response => {
          this.courseInfo = response.data.courseInfoVo
          // 获取所有课程分类
          subjectService.getAllSubject().then(response => {
            this.firstSubjectList = response.data.list
            // 遍历一级分类，让二级分类数组不为空，解决返回时二级分类为空的bug
            for (var i = 0; i < this.firstSubjectList.length; i++) {
              var first = this.firstSubjectList[i]
              if (this.courseInfo.subjectParentId == first.id) {
                this.secondSubjectList = first.children
              }
            }
          })
          // 也要遍历教师列表，解决返回时教师列表为空bug
          this.getAllTeacher()
        })
      },
      // 课程封面上传成功调用
      handleAvatarSuccess(response, file) {
        console.log(response) // 上传响应
        console.log(URL.createObjectURL(file.raw)) // base64编码
        this.courseInfo.cover = response.data.url
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      // 换一级分类时自动改变二级分类
      subjectLevelOneChanged(value) {
        for (var i = 0; i < this.firstSubjectList.length; i++) {
          var first = this.firstSubjectList[i]
          if (value === first.id) {
            this.secondSubjectList = first.children
            this.courseInfo.subjectId = ''
          }
        }
      },
      saveOrUpdate() {
        if (this.$route.params && this.$route.params.id) {
          // 更新
          courseService.updateCourseInfo(this.courseInfo).then(response => {
            this.$message({
              type: 'success',
              message: '更新课程信息成功!'
            });
            this.$router.push('/course/chapter/' + this.courseId)
          })
        } else {
          courseService.addCourseInfo(this.courseInfo).then(response => {
            this.$message({
              type: 'success',
              message: '添加课程信息成功!'
            });
          this.$router.push('/course/chapter/' + response.data.courseId)
          })
        }
      },
      // 获取所有教师的下拉列表
      getAllTeacher() {
        courseService.getAllTeacher().then(response => {
          this.teacherList = response.data.items
        })
      },
      // 获取所有课程分类
      getAllSubject() {
        subjectService.getAllSubject().then(response => {
          this.firstSubjectList = response.data.list
        })
      }
    }
  }
</script>
<style scoped>
  .tinymce-container {
    line-height: 29px;
  }
</style>
